package org.ling.xuan.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class FileLogUtil {
    public static final String logRoot = LxIoUtil.getWorkHome() + "/.lx/log/";
    
    private static String getLogFilePath(){
        String file = logRoot+"log-"+ DateUtil.today()+".log";
        FileUtil.mkParentDirs(file);
        return file;
    }
    
    public static void  logInfo(String filePath,String msg){
        FileUtil.appendString(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN),filePath, StandardCharsets.UTF_8);
        FileUtil.appendString(msg,filePath, StandardCharsets.UTF_8);
        FileUtil.appendString("\n",filePath, StandardCharsets.UTF_8);
    }
    public static void log(String message,Object... objects){
        String msg = message;
        if (objects != null) {
            Object[] os = new Object[objects.length];
            for (int i = 0; i < objects.length; i++) {
                if (objects[i] instanceof Exception) {
                    os[i] = ExUtil.getExMsg((Exception) objects[i], "\n");
                } else {
                    os[i] = objects[i];
                }
            }
            msg = StrUtil.format(message, os);
        }
        logInfo(getLogFilePath(),msg);
    }

    public static void log(File file, String message, Object... objects){
        String msg = message;
        if (objects != null) {
            Object[] os = new Object[objects.length];
            for (int i = 0; i < objects.length; i++) {
                if (objects[i] instanceof Exception) {
                    os[i] = ExUtil.getExMsg((Exception) objects[i], "\n");
                } else {
                    os[i] = objects[i];
                }
            }
            msg = StrUtil.format(message, os);
        }
        logInfo(file.getAbsolutePath(),msg);
    }
}
